package com.hengxinguotong.zhihuichengjian.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.Account;
import com.hengxinguotong.zhihuichengjian.bean.AccountRes;
import com.hengxinguotong.zhihuichengjian.bean.AuthorType;
import com.hengxinguotong.zhihuichengjian.bean.UserInfo;
import com.hengxinguotong.zhihuichengjian.utils.MD5Util;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.GradientTextView;
import com.lidroid.xutils.http.RequestParams;
import com.orhanobut.logger.Logger;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * @CopyRight 恒信国通信息科技
 * @Author wulei
 * @Date 2018/3/30
 */

public class TryUseActivity extends BaseActivity implements View.OnClickListener{
    @BindView(R.id.app_name)
    GradientTextView appName;
    @BindView(R.id.et_phone)
    HXEditTextView phoneEt;
    @BindView(R.id.close_rl)
    RelativeLayout closeRl;
    @BindView(R.id.et_virifi_code)
    HXEditTextView virifiCodeEt;
    @BindView(R.id.et_name)
    HXEditTextView nameEt;
    @BindView(R.id.et_company)
    HXEditTextView companyEt;
    @BindView(R.id.et_job)
    HXTextView jobEt;
    @BindView(R.id.get_virifi_code)
    HXTextView getVirifiCode;
    private List<AuthorType> jobList;
    private String phoneNumber = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_try_use);
        ButterKnife.bind(this);
        phoneEt.addTextChangedListener(new MyTextWatcher());
        int lightBlue = getResources().getColor(R.color.color_lightblue);
        int darkBlue = getResources().getColor(R.color.color_darkblue);
        appName.setColor(lightBlue, darkBlue);
        initJobList();
    }

    private class MyTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(start != before){
                closeRl.setVisibility(View.VISIBLE);
            }else{
                closeRl.setVisibility(View.GONE);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    @OnClick({R.id.get_virifi_code, R.id.try_use_bt, R.id.job_select, R.id.close_rl})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.get_virifi_code:
                if(Utils.isEmpty(phoneEt.getText().toString())){
                    showToast("请输入手机号码");
                }else{
                    if(time == 59){
                        phoneNumber = phoneEt.getText().toString();
                        sendCode("请稍等…");
                    }else{
                        showToast("验证码已发送，请稍候");
                    }
                }
                break;
            case R.id.try_use_bt:
                userRegister("请稍等…");
                break;
            case R.id.job_select:
                Intent intent = new Intent(this, MenuActivity.class);
                intent.putExtra("title", "职位列表");
                intent.putExtra("list", (Serializable) jobList);
                startActivityForResult(intent, 1);
                break;
            case R.id.close_rl:
                phoneEt.setText("");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(data != null){
            switch (requestCode){
                case 1:
                    AuthorType job = (AuthorType) data.getSerializableExtra("type");
                    jobEt.setText(job.getName());
                    break;
            }
        }
    }

    private void initJobList(){
        String[] jobArray = {"管理负责人","采购负责人","项目经理","技术负责人","施工员","安全员","质量员","材料员","监理员","其它"};
        jobList = new ArrayList<>();
        for(String job:jobArray){;
            AuthorType authorType = new AuthorType();
            authorType.setName(job);
            jobList.add(authorType);
        }
    }

    private int time = 59;
    private Handler handler = new Handler();
    private Runnable MyRunnable = new Runnable() {
        @Override
        public void run() {
            getVirifiCode.setText(time + "s");
            getVirifiCode.setTextColor(getResources().getColor(R.color.main_color));
            if(time > 0){
                time --;
                handler.postDelayed(this, 1000);
            }else{
                time = 59;
                getVirifiCode.setText("获取验证码");
                getVirifiCode.setTextColor(getResources().getColor(R.color.thirty_transparent_black));
            }
        }
    };

    /*
     *获取验证码
     */
    private void sendCode(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("mobile", phoneEt.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(getResources().getString(R.string.loading), this, "/user/sendCode", params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    int status = object.getInt("status");
                    if(status == 1){
                        handler.postDelayed(MyRunnable, 1000);
                    }
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    int status = object.getInt("status");
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private boolean checkContent(){
        if (Utils.isEmpty(phoneEt.getText().toString())){
            showToast("请填写手机号码");
            return false;
        }
        if(!Utils.isValidPhone(phoneEt.getText().toString())){
            showToast("手机号码格式不正确");
            return false;
        }
        if(Utils.isEmpty(phoneNumber)){
            showToast("请获取验证码");
            return false;
        }
        if(!phoneNumber.equals(phoneEt.getText().toString())){
            showToast("号码已更改，请重新获取验证码");
            return false;
        }
        if (Utils.isEmpty(virifiCodeEt.getText().toString())){
            showToast("请填写验证码");
            return false;
        }
        if(!Utils.isValidString(nameEt.getText().toString()) || !Utils.isValidString(companyEt.getText().toString()) || !Utils.isValidString(jobEt.getText().toString())){
            showToast("含有非法字符，请重新输入");
            return false;
        }
        if (Utils.isEmpty(nameEt.getText().toString())){
            showToast("请填写姓名");
            return false;
        }
        if (Utils.isEmpty(companyEt.getText().toString())){
            showToast("请填写公司名称");
            return false;
        }
        if (Utils.isEmpty(jobEt.getText().toString())){
            showToast("请填写职位");
            return false;
        }
        return true;
    }

    /*
     *注册
     */
    private void userRegister(String alert) {
        if (!checkContent()) {
            return;
        }

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("mobile", phoneEt.getText().toString());
            jsonObject.put("code", virifiCodeEt.getText().toString());
            jsonObject.put("name", nameEt.getText().toString());
            jsonObject.put("company", companyEt.getText().toString());
            jsonObject.put("position", jobEt.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(getResources().getString(R.string.loading), this, "/user/userRegister", params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(!Utils.isEmpty(json)){
                    AccountRes accountRes = new Gson().fromJson(json, AccountRes.class);
                    if(accountRes.getStatus() == 1){
                        Account account = accountRes.getValue();
                        showToast("您的用户名为：" + account.getUserName() + "\n您的密码为：" + account.getUserPassword());
//                        SPUtil.put(TryUseActivity.this, "userName", account.getUserName());
                        initLogin(account.getUserName(), account.getUserPassword());
                    }else{
                        showToast(accountRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    int status = object.getInt("status");
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /*
     *获取登录个人信息
     */
    private void initLogin(String userName, String passWord) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userName", userName);
            jsonObject.put("userPassword", MD5Util.getMD5(userName + passWord));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData("登录中 . . .", TryUseActivity.this, "/user/login", params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String status = object.getString("status");
                    String msg = object.getString("msg");
                    if ("1".equals(status)) {
                        Gson gson = new Gson();
                        UserInfo UserInfo = gson.fromJson(json, UserInfo.class);
                        String userId = UserInfo.value.getUserId();
                        SPUtil.put(TryUseActivity.this, "userId", UserInfo.value.getUserId());
                        // 调用 Handler 来异步设置别名
                        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, userId));
//                        SPUtil.put(TryUseActivity.this, "workType", UserInfo.value.getPerson().getWorkType());
                        SPUtil.put(TryUseActivity.this, "level", UserInfo.value.getLevel());
                        if(UserInfo.value.getLevel() == 1){
//                            SPUtil.put(TryUseActivity.this, "areaName", UserInfo.value.getLevelName());
                            SPUtil.put(TryUseActivity.this, "cityId", UserInfo.value.getLevelId());
                        }else if(UserInfo.value.getLevel() == 2){
                            SPUtil.put(TryUseActivity.this, "areaName", UserInfo.value.getLevelName());
                            SPUtil.put(TryUseActivity.this, "areaId", UserInfo.value.getLevelId());
                        }else if(UserInfo.value.getLevel() == 3){
//                            SPUtil.put(TryUseActivity.this, "vedio_ip", UserInfo.value.getVideo().getIp());
//                            SPUtil.put(TryUseActivity.this, "vedio_port", UserInfo.value.getVideo().getPort());
//                            SPUtil.put(TryUseActivity.this, "vedio_username", UserInfo.value.getVideo().getUsername());
//                            SPUtil.put(TryUseActivity.this, "vedio_password", UserInfo.value.getVideo().getPassword());
                        }
                        SPUtil.put(TryUseActivity.this, "levelName", UserInfo.value.getLevelName());
                        SPUtil.put(TryUseActivity.this, "userName", UserInfo.value.getUserName());
                        SPUtil.put(TryUseActivity.this, "realName", UserInfo.value.getRealName());
                        SPUtil.put(TryUseActivity.this, "uuid", UserInfo.value.getUuid());
                        SPUtil.put(TryUseActivity.this, "orgid", UserInfo.value.getOrgId());
                        SPUtil.put(TryUseActivity.this, "constructionid", UserInfo.value.getLevelId());
                        SPUtil.put(TryUseActivity.this, "json", json);
                        getMenuList(UserInfo.value.getUserId());

                    } else if ("0".equals(status)) {
                        Toast.makeText(TryUseActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(TryUseActivity.this, "登录失败:" + e.toString(), Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String status = object.getString("status");
                    String msg = object.getString("msg");
                    Toast.makeText(TryUseActivity.this, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(TryUseActivity.this, "登录失败:" + e.toString(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /*
     *获取首页菜单权限信息
     */
    private void getMenuList(String userId) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("userId", userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(getResources().getString(R.string.loading), TryUseActivity.this, "/authority/queryMenuList/" + SPUtil.getString(TryUseActivity.this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                SPUtil.put(TryUseActivity.this, "authority", json);
                Intent intent = new Intent();
                intent.setClass(TryUseActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    String TAG = "JPush";
    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs ;
            switch (code) {
                case 0:
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    Logger.d("Set tag and alias success" + code + alias + tags);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;
                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };
}
